﻿using System;
using System.Collections.Generic;

namespace RestUpMVC.Representation
{
    public interface IRepresentationFactory
    {
        IRepresentation GetRepresentationForContentType(string contentType, object resource);
        IRepresentation EmptyRepresentation { get; }
        void Add(IRepresentation representation);
        bool RepresentationForContentTypeExists(string contentType);
    }

    internal class RepresentationFactory : IRepresentationFactory
    {
        private IDictionary<string, Type> _representations = new Dictionary<string, Type>(StringComparer.OrdinalIgnoreCase);

        public IRepresentation GetRepresentationForContentType(string contentType, object resource)
        {
            const string defaultType = "application/json";
            if (!RepresentationForContentTypeExists(contentType))
            {
                contentType = defaultType;
            }
            var representation = (IRepresentation) _representations[contentType].GetConstructor(Type.EmptyTypes).Invoke(null);
            representation.SetResource(resource);
            return representation;
        }

        public IRepresentation EmptyRepresentation { get { return new EmptyRepresentation(); } }

        public void Add(IRepresentation representation)
        {
            if (representation == null) throw new ArgumentNullException("representation");
            if (_representations.ContainsKey(representation.ContentType))
            {
                throw new InvalidOperationException(RestUpMVCResource.RepresentationFactory_AddInvalidOperationException);
            }

            _representations.Add(representation.ContentType, representation.GetType());
        }

        public bool RepresentationForContentTypeExists(string contentType)
        {
            if (contentType == null) throw new ArgumentNullException("contentType");
            return _representations.ContainsKey(contentType);
        }
    }
}